//
//  FileManagerTool.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/4/5.
//

import Foundation
// MARK: - 文件管理工具基类
class FileManagerTool {
    /// 根目录类型
    enum Directory {
        case documents
        case caches
        
        var url: URL {
            switch self {
            case .documents:
                return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            case .caches:
                return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
            }
        }
    }
    
    /// 创建子目录（如果不存在）
    static func createSubdirectoryIfNeeded(at directory: Directory, subdirectory: String) -> URL? {
        let url = directory.url.appendingPathComponent(subdirectory)
        guard !FileManager.default.fileExists(atPath: url.path) else { return url }
        
        do {
            try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
            return url
        } catch {
            showLog("❌ 创建目录失败: \(error) - 路径: \(url.path)")
            return nil
        }
    }
    
    
    // 统一文件删除方法
    static func deleteFile(
        subdirectory: String,
        fileName: String,
        in directory: Directory = .documents
    ) -> Bool {
        let fileURL = directory.url
            .appendingPathComponent(subdirectory)
            .appendingPathComponent(fileName)
        
        guard FileManager.default.fileExists(atPath: fileURL.path) else {
            showLog("⚠️ 文件不存在: \(fileURL.path)")
            return false
        }
        
        do {
            try FileManager.default.removeItem(at: fileURL)
            showLog("✅ 文件删除成功: \(fileName)")
            return true
        } catch {
            showLog("❌ 文件删除失败: \(error)")
            return false
        }
    }
    
    /// 获取目录下所有文件
    static func listFiles(
        in subdirectory: String,
        directory: Directory = .documents
    ) -> [String] {
        let dirURL = directory.url.appendingPathComponent(subdirectory)
        
        do {
            return try FileManager.default.contentsOfDirectory(atPath: dirURL.path)
        } catch {
            showLog("❌ 获取文件列表失败: \(error)")
            return []
        }
    }
    
    // MARK: - 文件信息获取
    /// 获取文件元数据
    static func getFileMetadata(
        subdirectory: String,
        fileName: String,
        directory: Directory = .documents
    ) -> (size: Int64, modifiedDate: Date)? {
        let fileURL = directory.url
            .appendingPathComponent(subdirectory)
            .appendingPathComponent(fileName)
        
        guard FileManager.default.fileExists(atPath: fileURL.path) else {
            showLog("⚠️ 文件不存在: \(fileURL.path)")
            return nil
        }
        
        do {
            let attributes = try FileManager.default.attributesOfItem(atPath: fileURL.path)
            let size = attributes[.size] as? Int64 ?? 0
            let modifiedDate = attributes[.modificationDate] as? Date ?? Date()
            return (size, modifiedDate)
        } catch {
            showLog("❌ 获取文件信息失败: \(error)")
            return nil
        }
    }
    
    /// 获取文件大小（单位自动转换）
    static func getFileSizeFormatted(
        subdirectory: String,
        fileName: String,
        directory: Directory = .documents
    ) -> String {
        guard let metadata = getFileMetadata(subdirectory: subdirectory, fileName: fileName, directory: directory) else {
            return "未知大小"
        }
        
        return ByteCountFormatter.string(
            fromByteCount: metadata.size,
            countStyle: .file
        )
    }
}
